package cn.linshu.security.jwt.config;

import cn.linshu.security.jwt.component.JwtAuthenticationTokenFilter;
import cn.linshu.security.jwt.component.RestAuthenticationEntryPoint;
import cn.linshu.security.jwt.component.RestfulAccessDeniedHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * -*- coding: utf-8 -*-
 *
 * @Author linnin
 * @Name springboot3-labs-master
 * @Time 2025/2/3 23:46
 * @Note
 * @For
 * @Out Copyright© 2025 linnin
 */
@Configuration
public class SecurityConfig {
    @Autowired
    private IgnoreUrlsConfig ignoreUrlsConfig;
    @Autowired
    private RestfulAccessDeniedHandler restfulAccessDeniedHandler;
    @Autowired
    private RestAuthenticationEntryPoint restAuthenticationEntryPoint;
    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    @Bean
    SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.authorizeHttpRequests(registry -> {
                    //不需要保护的资源路径允许访问
                    for (String url : ignoreUrlsConfig.getUrls()) {
                        registry.requestMatchers(url).permitAll();
                    }
                    //允许跨域请求的OPTIONS请求
                    registry.requestMatchers(HttpMethod.OPTIONS).permitAll();
                    //添加测试权限
                    registry.requestMatchers("/api/v1/test").hasAuthority("TEST_ROLE");
//                    registry.requestMatchers("/api/v1/test").hasRole("TEST_ROLE");
                    //任何请求需要身份认证
                    registry.anyRequest().authenticated();
                })
                //关闭跨站请求防护
                .csrf(AbstractHttpConfigurer::disable)
                //修改Session生成策略为无状态会话
                .sessionManagement(configurer -> configurer.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                //自定义权限拒绝处理类
                .exceptionHandling(configurer -> configurer.accessDeniedHandler(restfulAccessDeniedHandler).authenticationEntryPoint(restAuthenticationEntryPoint))
                //自定义权限拦截器JWT过滤器
                .addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
        return httpSecurity.build();
    }
}
